home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!genesis.demon.co.uk
- From: Lawrence Kirby <fred@genesis.demon.co.uk>
- Newsgroups: comp.lang.c
- Subject: Re: How to detect if a number has fractions
- Date: Sun, 14 Apr 96 11:07:25 GMT
- Organization: none
- Message-ID: <829480045snz@genesis.demon.co.uk>
- References: <4klb63$h4e@gate.compart.fi>
- Reply-To: fred@genesis.demon.co.uk
- X-NNTP-Posting-Host: genesis.demon.co.uk
- X-Newsreader: Demon Internet Simple News v1.27
- X-Mail2News-Path: genesis.demon.co.uk
-
- In article <4klb63$h4e@gate.compart.fi>
- joonas.kervinen@pcb.compart.fi "joonas kervinen" writes:
-
- >Here's a small detail that's bugging me: How do I detect in Borland C
- >(BCC4.5 or 5.0) whether a double value has fractions. And I mean
- >quickly, not using time consuming floating point functions (floor()
- >ceil() etc.).
-
- These functions are probably your best method. Have you actually timed them
- or do you simply believe they are slow because they are functions? floor(),
- ceil() and modf() are all possibilities.
-
- The question though is why you would want to do this. Floating point
- arithmetic is inherently inaccurate and not even guaranteed to be able
- to represent whole numbers precisely (although your particular implementation
- might provide some guarantees in that area). So even using floor() etc.
- you may not get any meaningful results.
-
- >I got many replies using something like:
- >if (doublenum==(double)(int)doublenum)
- > puts("no fractions");
- >
- >But unfortunately it does work for numbers below (about) 32000. Using
- >long helps a little but not all. So the question remains.
- >
- >Another addition: I'd also like to know how many faction (like 3 in
- >23.234) a double contains.
-
- Very few decimal fractions can be represented precisely in binary (which is
- how floating point numbers are represented internally). For instance the
- binary representation of 1.0/10.0 is an infinite recurring expansion
- which the system will approximate to the precision of the floating point
- format used. If you try to convert that number back to decimal you will get
- a long expansion that is close to 0.1. To make your question meaningful
- you must add extra constraints e.g. convert to decimal with a limited
- number of decimal places or significant figures, eliminate trailing zeros
- (after the decimal point) and then see how many digits you have after the
- point.
-
- --
- -----------------------------------------
- Lawrence Kirby | fred@genesis.demon.co.uk
- Wilts, England | 70734.126@compuserve.com
- -----------------------------------------
-